package com.example.comic

import android.content.Intent
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.support.v4.app.Fragment
import android.view.Menu
import android.view.MenuItem
import com.example.comic.adpter.ViewPagerAdapter
import com.example.comic.mvp.view.AboutActivity
import com.example.comic.mvp.view.HomeFragment
import com.example.comic.mvp.view.RankFragment
import com.example.comic.mvp.view.SortFragment
import kotlinx.android.synthetic.main.activity_main.*
import kotlinx.android.synthetic.main.content_main.*

class MainActivity : AppCompatActivity() {
    val strings: ArrayList<Int> = arrayListOf(R.string.tab_one, R.string.tab_two, R.string.tab_three)

    companion object {
        val TYPE_MY: String = "my"
        val TYPE_ROOM: String = "room"
        val TYPE: String = "Type"
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        init()
    }

    private fun init() {
        toolbar.setTitle(R.string.toolbar_title)
        toolbar.title = resources.getString(R.string.toolbar_title)
//        toolbar.subtitle = resources.getString(R.string.toolbar_subtitle)
        setSupportActionBar(toolbar)
        val fragments = ArrayList<Fragment>()
        fragments.add(HomeFragment())
        fragments.add(RankFragment())
        fragments.add(SortFragment())
        val titles: List<String> = strings.map(this::getString)
        viewPager.adapter = ViewPagerAdapter(fragments, titles, supportFragmentManager)
        viewPager.offscreenPageLimit = 2
        tab.setupWithViewPager(viewPager)
    }

    override fun onCreateOptionsMenu(menu: Menu?): Boolean {
        menuInflater.inflate(R.menu.menu_main, menu)
        return true
    }

    override fun onOptionsItemSelected(item: MenuItem?): Boolean {
        val intent = Intent(this, AboutActivity().javaClass)

        return when(item?.itemId) {
            R.id.menu_my -> {
                intent.putExtra(TYPE, TYPE_MY)
                startActivity(intent)
                true
            }
            R.id.menu_room -> {
                intent.putExtra(TYPE, TYPE_ROOM)
                startActivity(intent)
                true
            }
            else -> {
                super.onOptionsItemSelected(item)
            }
        }
    }

    override fun onMenuOpened(featureId: Int, menu: Menu?): Boolean {
        if (menu != null) {
            if (menu.javaClass.simpleName == "MenuBuilder") {
                var m = menu.javaClass.getDeclaredMethod("setOptionalIconsVisible", java.lang.Boolean.TYPE)
                m.isAccessible = true
                m.invoke(menu, true)
            }
        }

        return super.onMenuOpened(featureId, menu)
    }
}
